﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.SessionState;

namespace TidyBlog.MVC.WWW
{
    /// <summary>
    /// GetCaptcha 的摘要说明
    /// </summary>
    public class GetCaptcha : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            string formName = context.Request.QueryString["formName"];
            if (!String.IsNullOrEmpty(formName))
            {
                Captcha captcha = new Captcha(4);
                CaptchaManager.Write(formName, captcha.Value);

                var bgColor = (context.Request["bgColor"] ?? "255,255,255").Split(new[] { ',' });

                Image image = captcha.CreateImage(
                    Color.FromArgb(
                        Convert.ToInt32(bgColor[0]),
                        Convert.ToInt32(bgColor[1]),
                        Convert.ToInt32(bgColor[2])
                    ), 170, 15, 4, 5
                );
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Png);

                context.Response.Cache.SetNoStore();
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

                context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(stream.GetBuffer());

                stream.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}